#include "ff.h"
#include "heap.h"
#include "fatfs.h"
#include "string.h"
#include "song_list.h"
#include "util.h"

static void handler_err(void);

/**
  * @brief 歌单文件名
 */
/**
  * @brief 短文件名数组文件名
  * [str]11
  * song0_path
  * [str]11
  * song1_path
  */
const char IMapFileName[] = "imap";

/**
  * @brief  歌单文件名
  *         歌单文本文件 utf8
  */
const char PMapFileName[] = "pmap";


/**
 * @brief 扫描文件目录下的歌曲并生成歌单
 */
void update_song_list(const TCHAR *path)
{
    FIL *imap = cMalloc(sizeof(FIL));
    FIL *pmap = cMalloc(sizeof(FIL));

    wchar_t wIMapFileName[sizeof(IMapFileName) * 2];
    wchar_t wPMapFileName[sizeof(PMapFileName) * 2];

    /* 创建新歌单 */
    FRESULT fr = f_open(imap, str2wstr(wIMapFileName, IMapFileName), FA_CREATE_ALWAYS | FA_WRITE);
    if (fr != FR_OK)
    {
        handler_err();
    }
    fr = f_open(pmap, str2wstr(wPMapFileName, PMapFileName), FA_CREATE_ALWAYS | FA_WRITE);
    if (fr != FR_OK)
    {
        handler_err();
    }

    DIR *dir = cMalloc(sizeof(DIR));
    wchar_t *wstrtmp = cMalloc(256);
    int song_index = 1;
    unsigned int bw;
    FILINFO filInfo = {0};
    filInfo.lfname = cMalloc(256);
    filInfo.lfsize = 256;

    /* 扫描文件系统目录 */
    /* 打开目录 */
    f_opendir(dir, path);
    
    /* 读取文件 */
    f_readdir(dir, &filInfo);
    while (dir->sect != 0)
    {
        if (!(filInfo.fattrib & AM_DIR))
        {
            getPathExtName(wstrtmp, filInfo.fname);
            if (!wstrncmp(wtoUpper(wstrtmp), L"MP3", 3))
            {
                fr = f_write(imap, &filInfo.fname, 26, &bw);
                if (fr != FR_OK)
                {
                    handler_err();
                }
                f_printf(pmap, L"%d、%s\n", song_index, filInfo.lfname);
                song_index++;
            }
        }
        /* 读取文件 */
        f_readdir(dir, &filInfo);
    }

    f_close(imap);
    f_close(pmap);
    f_closedir(dir);

    cFree(imap);
    cFree(pmap);
    cFree(dir);
    cFree(wstrtmp);
    cFree(filInfo.lfname);
    return;
}

static void handler_err(void)
{
    while (1) {}
}